package com.example.victory.service;

import com.example.victory.config.ServiceError;
import com.example.victory.swagger.handler.AppCrmContractApiDelegate;
import com.example.victory.swagger.model.*;
import com.example.fintech.sdk.api.inner.security.model.User;
import com.example.fintech.sdk.common.collection.SortingUtils;
import com.example.fintech.sdk.common.exception.GlobalException;
import com.example.fintech.sdk.common.utils.MoneyHelper;
import com.example.fintech.sdk.common.web.ServiceHelper;
import com.example.fintech.sdk.inner.utils.web.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AppCrmContractService implements AppCrmContractApiDelegate {

    @Autowired
    InnerCrmContractService innerCrmContractService;

    @Autowired
    SessionService sessionService;

    @Override
    public ResponseEntity<ApiResponseListContract> contractList(ApiRequestContract param) {

        ApiRequestContractData data = param.getData();
        ServiceHelper.checkDataNotNull(data, "data.contractData");

        Integer pageIndex = data.getPageIndex();
        Integer pageSize = data.getPageSize();

        ServiceHelper.check(pageIndex != null && pageIndex > 0, "data.pageIndex");
        ServiceHelper.check(pageSize != null && pageSize > 0, "data.pageSize");

        String search = data.getSearch();

        User user = sessionService.getCurrentUserSession(true).getUser();
        String ryBh = user.getCrmId();

        if (StringUtils.isEmpty(ryBh)) {
            throw new GlobalException(ServiceError.CRM_ID_NOT_FOUND);
        }

        com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequestContract requestContract = new com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequestContract();
        com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequestContractData contractData = new com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequestContractData();
        contractData.setRyId(ryBh);
        contractData.setSearch(search);
        contractData.setPageIndex(1);
        contractData.setPageSize(100000);

        ResponseEntity<com.cgws.fintech.sdk.api.inner.crmapi.model.ApiResponseListContract> responseEntity = null;
        try {
            responseEntity = innerCrmContractService.contractList(requestContract.data(contractData));
            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null || responseEntity.getBody().getData() == null) {
                log.error("请求CRMAPI错误:resp={}", responseEntity.getBody());
                throw new GlobalException(ServiceError.REQUEST_CRMAPI_FAIL);
            }
        } catch (Exception e) {
            log.error("请求错误", e);
            throw new GlobalException(ServiceError.REQUEST_CRMAPI_FAIL);
        }

        List<com.cgws.fintech.sdk.api.inner.crmapi.model.ContractItem> contractItems = responseEntity.getBody().getData().getContract();

        List<com.cgws.fintech.sdk.api.inner.crmapi.model.ContractItem> needPaged = new ArrayList<>();

        // 截止日期倒序排序
        if (contractItems != null) {

            // 根据截止日期升序
            SortingUtils.sortAscNullLast(contractItems, o -> o.getExpireDate());

            // 30天之前日期
            String days30later = getMonthLater();

            // 获取30天之内的数据
            contractItems.forEach(one -> {
                if (one != null && StringUtils.isNotEmpty(one.getExpireDate()) && one.getExpireDate().compareTo(days30later) <= 0) {
                    needPaged.add(one);
                }
            });
        }

        List<ContractItem> items = new ArrayList<>();

        // 分页
        for (int i = (pageIndex - 1) * pageSize; i < pageIndex * pageSize && i < needPaged.size(); i++) {
            ContractItem item = new ContractItem();
            BeanUtils.copyProperties(needPaged.get(i), item);

            item.setTransactionAmount(StringUtils.isNotEmpty(item.getTransactionAmount()) ?
                    MoneyHelper.formatMoney(new BigDecimal(item.getTransactionAmount().trim())) : ""); // 金额格式化

            items.add(item);

        }

        return ResponseEntity.ok(new ApiResponseListContract().data(new ApiResponseListContractData().contract(items)));
    }

    private String getMonthLater() {
        Date now = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(now);
        calendar.add(Calendar.DAY_OF_YEAR, 30);

        SimpleDateFormat sdfMonth = new SimpleDateFormat("yyyyMMdd");
        return sdfMonth.format(calendar.getTime());
    }

    @Override
    public ResponseEntity<ApiResponseListCustomer> customerList(ApiRequestContract param) {

        ApiRequestContractData data = param.getData();
        ServiceHelper.checkDataNotNull(data, "data.contractData");

        Integer pageIndex = data.getPageIndex();
        Integer pageSize = data.getPageSize();
        ServiceHelper.check(pageIndex != null && pageIndex > 0, "data.pageIndex");
        ServiceHelper.check(pageSize != null && pageSize > 0, "data.pageSize");

        // 客户号不能为空
        String search = data.getSearch();
        ServiceHelper.checkDataNotNull(search, "data.search");

        User user = sessionService.getCurrentUserSession(true).getUser();
        String ryBh = user.getCrmId();

        if (StringUtils.isEmpty(ryBh)) {
            throw new GlobalException(ServiceError.CRM_ID_NOT_FOUND);
        }

        com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequestContract request = new com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequestContract();
        com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequestContractData requestData = new com.cgws.fintech.sdk.api.inner.crmapi.model.ApiRequestContractData();
        requestData.setRyId(ryBh);
        requestData.setSearch(search);
        requestData.setPageIndex(pageIndex);
        requestData.setPageSize(pageSize);

        ResponseEntity<com.cgws.fintech.sdk.api.inner.crmapi.model.ApiResponseListCustomer> responseEntity;

        try {
            responseEntity = innerCrmContractService.customerList(request.data(requestData));
            if (responseEntity.getStatusCode() != HttpStatus.OK || responseEntity.getBody() == null || responseEntity.getBody().getData() == null) {
                log.error("请求CRMAPI错误:resp={}", responseEntity.getBody());
                throw new GlobalException(ServiceError.REQUEST_CRMAPI_FAIL);
            }
        } catch (Exception e) {
            log.error("请求错误", e);
            throw new GlobalException(ServiceError.REQUEST_CRMAPI_FAIL);
        }

        List<CustomerItem> items = new ArrayList<>();
        List<com.cgws.fintech.sdk.api.inner.crmapi.model.CustomerItem> crmItems = responseEntity.getBody().getData().getItems();

        if (crmItems != null) {
            crmItems.forEach(one -> {
                CustomerItem item = new CustomerItem();
                BeanUtils.copyProperties(one, item);

                // 金额格式化
                item.setTransactionAmount(StringUtils.isNotEmpty(item.getTransactionAmount()) ?
                        MoneyHelper.formatMoney(new BigDecimal(item.getTransactionAmount().trim())) : "");
                item.setSettleAmount(StringUtils.isNotEmpty(item.getSettleAmount()) ?
                        MoneyHelper.formatMoney(new BigDecimal(item.getSettleAmount().trim())) : "");

                items.add(item);
            });
        }

        return ResponseEntity.ok(new ApiResponseListCustomer().data(new ApiResponseListCustomerData().items(items)));
    }
}
